package com.scpii.api.common.auth.token;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Component;

import com.scpii.api.common.auth.AuthorizationRequest;
import com.scpii.api.common.auth.client.ClientDetailsService;

@Component
public class CompositeTokenGranter implements TokenGranter, InitializingBean {

	private List<TokenGranter> tokenGranters;

	@Resource(name = "clientAuthenticationManager")
	private AuthenticationManager authenticationManager;

	@Resource(name = "defaultTokenServices")
	private AuthorizationServerTokenServices tokenServices;

	@Resource(name = "defaultClientDetailsService")
	private ClientDetailsService clientDetailsService;

	public AuthAccessToken grant(String grantType,
			AuthorizationRequest authorizationRequest) {
		for (TokenGranter granter : tokenGranters) {
			AuthAccessToken grant = granter.grant(grantType,
					authorizationRequest);
			if (grant != null) {
				return grant;
			}
		}
		return null;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		tokenGranters = new ArrayList<TokenGranter>();
		tokenGranters.add(new ResourceOwnerPasswordTokenGranter(
				authenticationManager, tokenServices, clientDetailsService));
		tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices,
				clientDetailsService));
		tokenGranters.add(new ThirdPartyTokenGranter(authenticationManager,
				tokenServices, clientDetailsService));
		tokenGranters.add(new RefreshTokenGranter(tokenServices,
				clientDetailsService));
	}

}
